package br.com.sgi.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import br.com.sgi.dao.DaoGenerico;



public abstract class DaoGenericoImpl<T> implements DaoGenerico<T> {

	private static final long serialVersionUID = 6397851086603565823L;

	@PersistenceContext
	private EntityManager entityManager;
	
	private Class<T> persistentClass;
	
	
	 public DaoGenericoImpl() {
	        Type t = getClass().getGenericSuperclass();
	        ParameterizedType pt = (ParameterizedType) t;
	        persistentClass = (Class) pt.getActualTypeArguments()[0];
	    }
	

	public void setPersistentClass(Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	@Transactional
	public void save(T obj) {
		this.entityManager.persist(obj);
		this.entityManager.flush();
		
	}

	public final Class<T> getPersistentClass() {
		if (persistentClass == null) {
			throw new RuntimeException("É necessário invocar o método setPersistentClass(Class<T> clazz)");
		}
		return persistentClass;
	}
	
	public List<T> findAll() {
		Query query = this.entityManager.createQuery(" FROM " + getPersistentClass().getSimpleName());
		return query.getResultList();
	}
	
	public T findById(Serializable id) {
		return this.entityManager.find(getPersistentClass(), id);
	}
	
	@Transactional
	public <T> T update(T obj) {
		return  (T) this.entityManager.merge(obj);
	}

	@Transactional
	public void deleteById(Serializable id) {
		this.entityManager.remove(findById(id));
		
	}


}
